import asyncio
from concurrent.futures import ThreadPoolExecutor, ProcessPoolExecutor
import time
import random
import multiprocessing

# 创建线程池和进程池
thread_pool = ThreadPoolExecutor(max_workers=5)
process_pool = ProcessPoolExecutor(max_workers=multiprocessing.cpu_count())


# asyncio.get_event_loop 程序员创建事件循环；虽然还是用多线程和多进程，但可能切换机制更多是程序员控制




def cpu_bound_task(task_id):
    """模拟一个CPU密集型任务"""
    print(f"开始执行CPU密集型任务 {task_id}")
    result = sum(i * i for i in range(10**7))
    print(f"CPU密集型任务 {task_id} 执行完成")
    return f"CPU任务 {task_id} 的结果: {result}"

async def io_bound_task(task_id):
    """模拟一个IO密集型异步任务"""
    print(f"开始执行IO密集型任务 {task_id}")
    await asyncio.get_event_loop().run_in_executor(
        thread_pool,
        time.sleep,
        random.uniform(1, 3)
    )
    print(f"IO密集型任务 {task_id} 执行完成")
    return f"IO任务 {task_id} 的结果"

async def main():
    # 创建多个IO密集型任务
    io_tasks = [io_bound_task(i) for i in range(5)]

    # 创建多个CPU密集型任务
    cpu_tasks = [
        asyncio.get_event_loop().run_in_executor(process_pool, cpu_bound_task, i)
        for i in range(5)
    ]

    # 合并所有任务
    all_tasks = io_tasks + cpu_tasks

    # 异步执行所有任务
    results = await asyncio.gather(*all_tasks)

    # 打印结果
    for result in results:
        print(result)

if __name__ == "__main__":
    asyncio.run(main())
